<template>
  <div  style="width:100%;height:100%">
    <Portal to="right-disable"
     style="width:100%;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill content-nodata"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  :style="{height:gadgetHeight+ 'px',border:0}">
                                  
        <el-card shadow="never"
                 class="aui-card--fill content-card"
                 :style="{height:gadgetHeight+ 'px',border:0}">
                 
          <div :style="{height:gadgetHeight+ 'px',width:'100%'}">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName&& widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
                 <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <!-- <MoreMenu :gadgetId='id'
                      :gadgetType='gadgetInfo.com'
                      @updateQuery="query" /> -->
            </div>
            <div  v-if="Object.keys(formSchema).length > 0"  :style="{height:gadgetHeight+ 'px'}">
             
              <div class="control-section"  :style="{margin: '10px 10px',height:gadgetHeight-140+ 'px'}">
              <div class="content-wrapper"
                   style="padding:5px;width:100%;height:100%"
                   ref="content-wrapper">
                <fm-generate-form :data="formSchema"  style="height:100%;overflow: auto;"
                                  v-if="Object.keys(formSchema).length > 0"
                                  :remote="remoteFuncs"
                                  ref="generateForm">
                </fm-generate-form>             
              </div>
            </div>
            <span slot="footer"
                  v-if="Object.keys(formSchema).length > 0 && hasBtn"
                  style="float: right;margin-right:10px;margin-bottom:10px;">
              <el-button size="mini"
                         @click="resetFormView">{{$t('clear')}}</el-button>
              <el-button size="mini"
                         type="primary"
                         @click="addOrUpdateFormData">{{$t('submit')}}</el-button>
            </span>
            </div>
            <div v-else
                    class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
              </div>
          </div>

        </el-card>
      </DashboardInterceptConsumer>

    </Portal>

    <model slot="queryModel"
           :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />

  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import { defaultGadgetSettingList } from '@/utils/data-json'
import getDataset from './form-fuction'
import Cookies from 'js-cookie'
export default {
  mixins: [mixinGadgetViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      agreementoptions: [],
      gadgetSetting: {},
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'formviewdatagadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'formviewdatagadget' }).gadgetSetting
        }
      },
      formSchema: {},
      formViewData: {},
      formId: '',
      remoteFuncs: {
        func_options (resolve) {
          getDataset.clientList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        },
        clientList (resolve) {
          getDataset.timeZoneList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        }
      },
      jsonData: {},
      widgetName: '',
      userformDialogData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null
      }

    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.agreementFn()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 : this.pageFromType === 'report' ? (this.gadgetInfo.h * (this.rolHeight+10)-10 - 5) : ((this.gadgetInfo.h * 22) - (this.gadgetInfo.h * 0.1 *0.02 ) - 15)
  },
  updated () {
    // if (this.$refs['content-wrapper']) {
    //   let clientHeight = this.$refs['content-wrapper'].clientHeight
    //   this.gadgetHeight = clientHeight + 100
    // }
  },
  computed: {
    comDataList () {
      var _self = this
      var retdata = _self.dataList
      return retdata
    },
    hasBtn () {
      return this._.get(this.gadgetSetting, 'roles', [])
        .some(id => this.$store.state.user.roleList&&this.$store.state.user.roleList.some(({ id: i }) => i === id))
    }
  },
  methods: {

    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    queryModelPreview () {
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = this.pageFromType === 'report' ? (newH * (this.rolHeight+10)-10 - 5) : (newH * 22) - (newH * 0.1 *0.02 ) -15
      this.gadgetWidth = newWPx
    },
    apiConfig (res) {
      res.config && res.config.dataSource && res.config.dataSource.forEach(item => {
        item.headers.tenantCode = Cookies.get('tenant_code') || ''
        item.headers.timezoneOffset = this.$store.state.user.timezoneOffset ? this.$store.state.user.timezoneOffset : ''
        item.headers.token = Cookies.get('token') || ''
      })
      return res
    },
    agreementFn () {
      var _self = this
      _self.$interface.reports.getReportDataInfo({
        type: 'widget',
        gadgetId: '7962530e-f630-4bb4-8db8-2830642a0117'
      }).then(({ data: res }) => {
        var arr = []
        res.data.forEach(item => {
          var is = arr.find(i => i.label === item.agreement_category)
          if (!is) {
            var obj = {
              label: item.agreement_category,
              value: item.agreement_category_id,
              children: []
            }
            arr.push(obj)
          }
        })
        res.data.forEach(item => {
          var result = arr.find(i => {
            return i.label === item.agreement_category
          })
          if (result) {
            var obj = {
              label: item.agreement_name_formal,
              value: item.agreement_id
            }
            result.children.push(obj)
          }
        })
        _self.agreementoptions = arr
        _self.query()
      })
        .catch((e) => {

        })
    },
    resetData (formSetting) {
      var _self = this
      for (let i = 0; i < formSetting.list.length; i++) {
        try {
          let reg = RegExp(/agreementoptions/)
          if (reg.test(formSetting.list[i].model)) {
            if (formSetting.list[i].options.options) {
              formSetting.list[i].options.options = _self.agreementoptions
            }
          }
          if (formSetting.list[i].tableColumns && formSetting.list[i].tableColumns.length > 0) {
            formSetting.list[i].tableColumns.forEach(ii => {
              if (ii.model.includes('agreementoptions')) {
                ii.options.options = _self.agreementoptions
              }
            })
          }
        } catch (error) {
        }
      }
    },
    getJsonFormList (formCode) {
      var _self = this
      const params = { current: 1, size: 1, desc: 'create_time', formCode: formCode }
      _self.loading = true
      _self.$interface.reports.getFormDataListApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          _self.loading = false
          return _self.$message.error(res.msg)
        }
        _self.formSchema = _self.apiConfig(_self.gadgetSetting.formSchema)
        _self.resetData(_self.formSchema)
        if (res.data.records.length > 0) {
          _self.$nextTick(() => {
            try {
              _self.$refs.generateForm.setData(res.data.records[0].dataContent)
            } catch (error) { }
          })
          _self.formId = res.data.records[0].id
        }
        _self.loading = false
      }).catch(() => {
        _self.loading = false
      }).finally(() => {
        this.loading = false
        this.updateGadgetLoadingStatus(!this.loading)
      })
    },
    addOrUpdateFormData () {
      this.$refs.generateForm.getData().then((val) => {
        var params = {}
        if (this.formId) {
          params = { id: this.formId, dataContent: val }
        } else {
          params = {
            formCode: this.gadgetSetting.formCode,
            formVersion: this.gadgetSetting.formVersion,
            dataContent: val
          }
        }
        this.loading = true
        this.$interface.reports.addOrUpdateFormDataApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading = false
            return this.$message.error(res.msg)
          }
          this.formViewId = res.data.id
          this.loading = false
          this.$message.success(this.$t('success'))
        }).catch(() => {
          this.loading = false
        })
      })
    },
    resetFormView () {
      if (this.$refs.generateForm) {
        this.$refs.generateForm.reset()
      }
    },
    query (e) {
      // this.dataList = []
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.isHasData = false
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      this.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          _self.verifyHasData(res)

          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
            // this.$refs.generateForm.reset()
          }

          _self.getJsonFormList(_self.gadgetSetting.formCode)
          _self.$forceUpdate()
          if (res.name) {
            _self.widgetName = res.name
          } else if (this.wName) {
            _self.widgetName = this.wName
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
        })
        .catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
          }
          this.isHasData = false
          this.loading = false
          if (error.response && error.response.status === 504) {
            this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
          }
        }).finally(() => {
          this.autoRefreshQuery(e)
          this.updateGadgetLoadingStatus(!this.loading)
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.content-nodata {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  width: 100%;
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}
.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  /* display: flex;
  justify-content: space-between;
  align-items: center; */
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
